package org.cloud.jiangyouuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.cloud.jiangyoucommon.common.Result;
import org.cloud.jiangyoucommon.utils.AESUtils;
import org.cloud.jiangyoucommon.utils.SnowFlakeUtils;
import org.cloud.jiangyoucommon.utils.StringUtils;
import org.cloud.jiangyouuser.dto.LoginDTO;
import org.cloud.jiangyouuser.entity.pojo.User;
import org.cloud.jiangyouuser.mapper.UserMapper;
import org.cloud.jiangyouuser.service.UserService;
import org.cloud.jiangyouuser.vo.LoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 用户信息 Service层实现类
 * @Author: liupy
 * @Date: 2024/1/1
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param loginDTO 登录入参
     * @return
     */
    @Override
    public Result login(LoginDTO loginDTO) {
        String account = StringUtils.trim(loginDTO.getAccount());
        String password = StringUtils.trim(loginDTO.getPassword());

        // TODO 1.密码密文，需要先进行解密
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getAccount, account)
                .eq(User::getPassword, password));
        // TODO 2.登录成功携带token
        if (user == null) {
            log.error("登录失败，用户名或密码错误,account={}",account);
            return Result.fail("用户名或密码错误");
        }

        LoginVO loginVO = new LoginVO();
        BeanUtils.copyProperties(user,loginVO);
//        loginVO.setToken(token);
        // TODO 3.登录成功只携带部分信息，隐私数据不可携带，需写VO
        return Result.success(loginVO,"登录成功！");
    }

    /**
     * 用户注册
     * @param user 用户信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result register(User user) throws Exception {
        String account = StringUtils.trim(user.getAccount());
        String password = StringUtils.trim(user.getPassword());
        // 注册时，账号和密码不能为空
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            return Result.fail("账号或密码不能为空！");
        }

        // 密码长度只能在20位以内
        if (password.length() > 20) {
            return Result.fail("密码长度不能超过20位！");
        }

        // 1.对密码加密后进行存储
        String encryptPassword = AESUtils.getHashEncryptValue(password);
        user.setPassword(encryptPassword);
        // 2.生成用户唯一标识，即雪花id
        String userId = SnowFlakeUtils.getRandomId();
        user.setUserId(userId);
        userMapper.insert(user);
        // 3.注册成功后返回注册成功的信息
        return Result.success("注册成功！");
    }

    /**
     * 获取用户列表
     * @return
     */
    @Override
    public Result getAllUsers() {
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>());

        if (CollectionUtils.isEmpty(userList)) {
            log.error("用户列表为空");
            return Result.fail("用户列表为空");
        }

        return Result.success(userList);
    }

    /**
     * 根据id查询用户信息
     * @param userId 用户id
     * @return
     */
    @Override
    public Result queryById(String userId) {
        User user = userMapper.selectById(StringUtils.trim(userId));

        if (user == null) {
            log.error("用户不存在，userId={}", userId);
            return Result.fail("用户不存在");
        }

        return Result.success(user);
    }

    /**
     * 根据账号查询用户信息
     * @param account 账号
     * @return
     */
    @Override
    public Result queryByUserName(String account) {
        List<User> userList = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getAccount, StringUtils.trim(account)));

        if (CollectionUtils.isEmpty(userList)) {
            return Result.fail("该账号不存在");
        }

        return Result.success(userList.get(0));
    }
}
